<template>
  <a-modal :title="title" :width="width" :visible="visible" @cancel="handleCancel" :footer="null">
    <a-spin :spinning="confirmLoading">
      <div class="antd-modal-form">
        <a-steps :current="current">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" />
        </a-steps>
        <div class="steps-content" v-if="current==0">
          <a-checkbox-group v-model:value="formData.signingService" style="width: 100%;padding: 20px;" @change="handleCheckboxChange">
            <a-row>
              <a-col :span="6" v-for="item in signingServiceList" :key="item.value">
                <a-checkbox :value="item.value+'_'+item.text" class="ss-checkbox">{{item.text}}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </div>
        <div v-if="current==1">
          <div class="steps-content-desp" style="padding: 20px;">
            <span style="font-size: 16px"><strong>提示：</strong></span>
            <span>1、导入数据需要跟模板格式一样方可导入；</span>
            <span>2、单次导入最多1000条；</span>
            <span>3、选择文件，确认数据无误后点击“下一步”；</span>
          </div>
          <!--引用表格-->
          <BasicTable @register="registerTable">
            <!--插槽:table标题-->
            <template #tableTitle>
              <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls" >选择文件</j-upload-button>
            </template>
            <!--证件类型插槽-->
            <template #idCardTypeSlot="{record}">
              <span v-if="record.idCardType===1">身份证</span>
              <span v-if="record.idCardType===2">港澳台通行证</span>
              <span v-if="record.idCardType===3">护照</span>
              <span v-if="record.idCardType===4">军官证</span>
            </template>
          </BasicTable>
        </div>
        <div v-if="current==2">
          <a-result :status="returnData.successLines==0 ? 'warning' :  (returnData.errorLines==0 && returnData.repeatLines==0) ? 'success' : ''"
            :title="returnData.successLines==0 ? '数据未成功导入，详情如下：' : (returnData.errorLines==0 && returnData.repeatLines==0) ? '数据已全部成功导入！' : '数据部分成功导入！'"
            :sub-title="'成功条数：' + returnData.successLines +'条；' + '重复条数：' + returnData.repeatLines +'条；' + '错误条数：' + returnData.errorLines +'条；'"
          >
            <span v-html="returnData.errorMessage" />
            <template #extra>
              <a-button key="console" type="primary" @click="handleDone">完成</a-button>
              <a-button key="buy" @click="handleAgain">继续导入</a-button>
            </template>
          </a-result>
        </div>
        <div class="steps-action">
          <a-button v-if="current == 1" @click="prev">上一步</a-button>
          <a-button v-if="current == 0" style="margin-left: 10px" type="primary" @click="next" :disabled="nextDisabled">下一步</a-button>
          <a-button v-if="current == 1" style="margin-left: 10px" type="primary" @click="next" :disabled="nextDisabled2">下一步</a-button>
<!--          <a-button v-if="current == 2" style="margin-left: 10px" type="primary" @click="handleDone">完成</a-button>-->
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { defineExpose, reactive, ref } from "vue";
import { getSigningServiceList } from "/@/views/operation/serviceTask/ServiceTask.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { BasicTable } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { getImportUrl, handleImportList } from "/@/views/datas/signingMember/SigningMember.api";
import { importColumns } from "/@/views/datas/signingMember/SigningMember.data";

const title = ref<string>('');
  const width = ref<number>(1200);
  const visible = ref<boolean>(false);
  const disableSubmit = ref<boolean>(false);
  const emit = defineEmits(['register', 'success']);
  const confirmLoading = ref<boolean>(false);
  const { createMessage, createConfirm } = useMessage();
  const current = ref<number>(0);
  const signingServiceList = ref<any[]>([]);
  const nextDisabled = ref<boolean>(true);
  const nextDisabled2 = ref<boolean>(true);
  const formData = reactive<Record<string, any>>({
    signingService: '',//ID_name,ID_name 格式
    memberList: [],
  });
  const steps = ref<any>([
    {
      title: '请选择服务类型',
      content: '',
    },
    {
      title: '人才导入',
      content: '',
    },
    {
      title: '完成',
      content: '',
    },
  ]);
  const importMemberList = ref<any[]>([]);
  //注册table数据
  const { prefixCls, tableContext, onImportXls } = useListPage({
    tableProps: {
      title: '待导入人才列表',
      dataSource: importMemberList,
      columns: importColumns,
      canResize:false,
      useSearchForm: false,
      striped: true,
      showIndexColumn: true,
      showActionColumn: false,
      pagination: false,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const returnData = ref<any>({});//导入表格提交返回数据

  const next = async () => {
    //数据格式化
    let model = formData;
    if(!model || model==null || model.length===0){
      createMessage.warning("服务类型不能为空！");
    }
    //如果该数据是数组则转换为字符串类型
    if (model.signingService instanceof Array) {
      model.signingService = model.signingService.join(',');
    }
    console.log("---提交数据--：",model)
    if(current.value==0){
      current.value++;
      nextDisabled2.value = true;
      importMemberList.value = [];
      formData.memberList = [];
    }else {
      createConfirm({
        iconType: 'warning',
        title: '确认提交',
        content: '请仔细检查数据，确认无误后提交表格数据？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          confirmLoading.value = true;
          //提交数据
          handleImportList(model).then((res) => {
            if (res.success) {
              returnData.value = res.result;
              current.value++;
            } else {
              createMessage.warning(res.message);
            }
          }).finally(() => {
            confirmLoading.value = false;
          });
        }
      });
    }
  };
  const prev = () => {
    current.value--;
  };
  function handleAgain(){
    current.value = 0;
    emit('success');
  }
  function handleDone(){
    emit('success');
    visible.value = false;
  }

  function handleCheckboxChange(val){
    if(val.length > 0){
      nextDisabled.value = false;
    }else {
      nextDisabled.value = true;
    }
  }

  /**
   * 新增
   */
  async function add() {
    title.value = '人才批量导入';
    visible.value = true;
    current.value = 0;
    formData.signingService = [];
    //获取签约服务类型列表
    const res = await getSigningServiceList();
    if (!res || res.length == 0) {
      signingServiceList.value = [];
    } else {
      signingServiceList.value = res;
    }
  }

  /**
   * 取消按钮回调事件
   */
  function handleCancel() {
    visible.value = false;
  }

  /**
   * 导入成功之后数据展示
   */
  async function handleSuccess(data){
    if (data.success) {
      importMemberList.value = data.result;
      nextDisabled2.value = false;
    } else {
      nextDisabled2.value = true;
      importMemberList.value = [];
      createMessage.warning(data.message);
    }
    formData.memberList = importMemberList.value;
  }

  defineExpose({
    add,
    disableSubmit,
  });
</script>

<style lang="less" scoped>
  /**隐藏样式-modal确定按钮 */
  .jee-hidden {
    display: none !important;
  }

  .antd-modal-form {
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }

  .steps-content {
    margin-top: 16px;
    border: 1px dashed #e9e9e9;
    border-radius: 6px;
    background-color: #fafafa;
    min-height: 240px;
  }

  .ss-checkbox{
    border: 1px solid #eae8e8;
    border-radius: 5px;
    width: 90%;
    height: 32px;
    line-height: 32px;
    padding-left: 10px;
    margin-top: 10px;
  }
  .steps-action {
    margin-top: 24px;
    float: right;
  }

  [data-theme='dark'] .steps-content {
    background-color: #2f2f2f;
    border: 1px dashed #404040;
  }
  .image-tip-cla{
    margin-left: 70px;
    margin-top: 5px;
  }

  .steps-content-desp {
    margin-top: 16px;
    border: 1px dashed #e9e9e9;
    border-radius: 6px;
    background-color: #fafafa;
  }
</style>
